package com.guigutool.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigutool.reggie.common.R;
import com.guigutool.reggie.dto.DishDto;
import com.guigutool.reggie.entity.Category;
import com.guigutool.reggie.entity.Dish;
import com.guigutool.reggie.service.CategoryService;
import com.guigutool.reggie.service.DishFlavorService;
import com.guigutool.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author: KingWang
 * @Date: 2023/3/13
 * @Desc: 菜品管理
 **/
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody  DishDto dishDto){
        log.info("新增菜品");
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功,Id:" + dishDto.getId());
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody  DishDto dishDto){
        log.info("修改菜品保存");
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功,Id:" + dishDto.getId());
    }


    /**
     * 菜品信息分页查询
     * @param name
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(String name, int page,int pageSize){
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null, Dish::getName,name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo, queryWrapper);

        //对象拷贝
        Page<DishDto> dishDtoPage = new Page<>(page,pageSize);
        BeanUtils.copyProperties(pageInfo,dishDtoPage, "records");
        List<DishDto> dishDtos = pageInfo.getRecords().stream().map(x->{
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(x, dto);
            Long categoryId = x.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(Objects.nonNull(category)){
                dto.setCategoryName(category.getName());
            }
            return dto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dishDtos);

        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

//    /**
//     * 根据条件查询对应的菜品数据
//     * @param dish
//     * @return
//     */
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(null != dish.getCategoryId(),Dish::getCategoryId,dish.getCategoryId());
//        queryWrapper.eq(Dish::getStatus,1); //添加查询状态为1
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> dishList = dishService.list(queryWrapper);
//
//        return R.success(dishList);
//    }

    /**
     * 根据条件查询对应的菜品数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){

        List<DishDto> dishDtoList = null;

        String key = "dish:" + dish.getCategoryId();
        //先从redis中查询缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //如果存在，直接返回，无需查询数据库
        if(Objects.nonNull(dishDtoList)){
            return R.success(dishDtoList);
        }


        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != dish.getCategoryId(),Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1); //添加查询状态为1
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(queryWrapper);
        dishDtoList = dishList.stream().map(x->{
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(x, dto);
            Long categoryId = x.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(Objects.nonNull(category)){
                dto.setCategoryName(category.getName());
            }

            Long dishId = x.getId();
            DishDto dishWithFlavor = dishService.getByIdWithFlavor(dishId);
            dto.setFlavors(dishWithFlavor.getFlavors());

            return dto;
        }).collect(Collectors.toList());

        //如果不存在，则查询数据库，并将查询到的菜品数据缓存到redis
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }

}
